package tw.raybird.walker.officereader;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;



import com.healthmarketscience.jackcess.Column;
import com.healthmarketscience.jackcess.Database;
import com.healthmarketscience.jackcess.Table;

public class AccessReader implements Reader {

	private Logger logger;

	public AccessReader() {
		logger = Logger.getRootLogger();
	}

	@Override
	public String read(File file) {
		return openDatabase(file);
	}

	/**
	 * 讀取資料庫內容。
	 * @param file
	 * @return
	 */
	private String openDatabase(File file) {
		if(!file.exists()){
			return "";
		}
		StringBuilder builder = new StringBuilder();
		Database database = null;
		try {
			database = Database.open(file);
			Set<String> tableNames = database.getTableNames();
			if (tableNames != null && tableNames.size() > 0) {
				for (String name : tableNames) {
					builder.append("Table Name: "+name+",\n");
					Table table = database.getTable(name);
					List<Column> columns = table.getColumns();
					if (columns != null && columns.size() > 0) {
						builder.append("Column Name: ");
						for (Column column : columns) {
							builder.append(column.getName()+",");
						}
						builder.append("\n");
						table.reset();
						Map<String, Object> map = null;
						while ((map = table.getNextRow()) != null) {
							builder.append("Row Value: ");
							Set<String> keySet = map.keySet();
							for (String key : keySet) {
								builder.append(map.get(key)+",");
							}
							builder.append("\n");
						}						
					}
				}
			}

		} catch (Exception e) {
			logger.warn("", e);
		} finally {
			Util.close(database);
		}
		String string = builder.toString();
		builder = null;
		System.gc();
		return string;
	}
}
